package com.eric.statemachinedemo.exception;

import com.eric.statemachinedemo.constant.ResponseCodeEnum;
import com.eric.statemachinedemo.model.response.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 使用EXCEPTIONS存放异常类型和错误代码的映射，并且线程安全
     */
    private static final Map<Class<? extends Throwable>, ResponseCodeEnum> EXCEPTIONS = new HashMap<>();

    /**
     * 捕获通用的Exception异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception e) {
        LOGGER.error("catch exception : {}\r\nexception: ",e.getMessage(), e);
        ResponseCodeEnum resultCode = EXCEPTIONS.getOrDefault(e.getClass(), ResponseCodeEnum.SERVER_ERROR);
        return new ResponseResult(resultCode);
    }

    /**
     * 针对ProcessException异常进行捕获处理
     */
    @ExceptionHandler(ProcessException.class)
    public ResponseResult processException(ProcessException e) {
        LOGGER.error("catch exception : {}\r\nexception: ", e.getMessage(), e);
        ResponseCodeEnum responseCode = e.getResponseCode();
        return new ResponseResult(responseCode);
    }

    //在这里加入一些不可预知的基础异常类型判断
    static{
        EXCEPTIONS.put(HttpMessageNotReadableException.class, ResponseCodeEnum.SERVER_ERROR);
    }
}
